package com.zcy.tag;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

import java.sql.ResultSet;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

public class DbconnTag extends TagSupport {

	private String driver;
	private String user;
	private String pwd;
	private String sql;
	private String url;

	Connection conn = null;
	Statement st = null;
	ResultSet ret = null;

	public void setUrl(String url) {
		this.url = url;
	}

	public void setDriver(String driver) {
		this.driver = driver;
	}

	public void setUser(String user) {
		this.user = user;
	}

	public void setPwd(String pwd) {
		this.pwd = pwd;
	}

	public void setSql(String sql) {
		this.sql = sql;
	}

	@Override
	public int doEndTag() throws JspException {
		try {
			Class.forName(this.driver);
			conn = DriverManager.getConnection(url, user, pwd);
			st = conn.createStatement();
			ret = st.executeQuery(sql);

			if (ret != null) {
				while (ret.next()) {
					System.out.println(ret.getString("tname"));
					pageContext.getOut().print(ret.getString("tname") + "<br>");
				}
			}

			return EVAL_PAGE;

		} catch (Exception e) {
			e.printStackTrace();
			return SKIP_PAGE;
		}finally{
			if(ret!=null)
				try {
					ret.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
				if(st!=null)
					try {
						st.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				if(conn!=null)
					try {
						conn.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
			
		}

	}
}
